#include <QAction>
#include <QHash>
#include "actionpool.h"

namespace ShUi
{

class ActionPoolImpl : public Impl<ActionPool>
{
public:
    QHash<QString, QAction*> _actions;
};

ActionPool::ActionPool(QObject *parent) :
    QObject(parent)
{
    SH_I(ActionPool);
    Q_UNUSED(d);
}

ActionPool::~ActionPool()
{
}

QAction* ActionPool::action(const QString& name)
{
    SH_D(ActionPool);
    QHash<QString, QAction*>::iterator iter = d->_actions.find(name);
    return iter != d->_actions.end() ? iter.value() : SH_NULL;
}

void ActionPool::createActions()
{
    QAction* action = new QAction(tr("config"), this);
    action->setObjectName("config");
    insertAction(action);
}

bool ActionPool::insertAction(QAction* action)
{
    SH_D(ActionPool);
    QHash<QString, QAction*>::iterator iter = d->_actions.find(action->objectName());
    if (iter != d->_actions.end())
    {
	SH_ASSERT(false);
	return false;
    }
    d->_actions.insert(action->objectName(), action);
    connect(action, SIGNAL(triggered()), this, SLOT(onTriggered()));
    return true;
}

bool ActionPool::removeAction(QAction* action)
{
    SH_D(ActionPool);
    QHash<QString, QAction*>::iterator iter = d->_actions.find(action->objectName());
    if (iter == d->_actions.end())
    {
	SH_ASSERT(false);
	return false;
    }
    d->_actions.erase(iter);
    disconnect(action, SIGNAL(triggered()), this, SLOT(onTriggered()));
    return true;
}

void ActionPool::onTriggered()
{
    QString command = sender()->objectName();
    emit commandIssued(command);
}

} // namespace ShUi
